package com.lin.project.cloudnative.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lin.project.cloudnative.annotation.AuthCheck;
import com.lin.project.cloudnative.common.BaseResponse;
import com.lin.project.cloudnative.common.DeleteRequest;
import com.lin.project.cloudnative.common.ErrorCode;
import com.lin.project.cloudnative.common.ResultUtils;
import com.lin.project.cloudnative.constant.CommonConstant;
import com.lin.project.cloudnative.exception.BusinessException;
import com.lin.project.cloudnative.model.dto.post.PostAddRequest;
import com.lin.project.cloudnative.model.dto.post.PostQueryRequest;
import com.lin.project.cloudnative.model.dto.post.PostUpdateRequest;
import com.lin.project.cloudnative.model.entity.Post;
import com.lin.project.cloudnative.model.entity.User;
import com.lin.project.cloudnative.service.PostService;
import com.lin.project.cloudnative.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 帖子接口
 */
@RestController
@RequestMapping("/post")
@Slf4j
public class PostController {
    @Resource
    private PostService postService;

    @Resource
    private UserService userService;

    /**
     *
     *
     * @description: 添加帖子
     * @param postAddRequest
     * @param request
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/17 19:58
     */

    @PostMapping("/add")
    public BaseResponse<Long> addPost(@RequestBody PostAddRequest postAddRequest, HttpServletRequest request){
        if(postAddRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post=new Post();
        BeanUtils.copyProperties(postAddRequest,post);
        //校验
        postService.validPost(post,true);
        User loginUser = userService.getLoginUser(request);
        post.setUserId(loginUser.getId());
        boolean save = postService.save(post);
        if(!save){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        Long id = post.getId();
        return ResultUtils.success(id);
    }

    /**
     *
     *
     * @description: 删除帖子
     * @param deleteRequest
     * @param request
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/17 20:07
     */

    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePost(@RequestBody DeleteRequest deleteRequest,HttpServletRequest request){
        if(deleteRequest==null || deleteRequest.getId()<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Long id = deleteRequest.getId();
        //判断是否存在
        Post post = postService.getById(id);
        if(post==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //仅管理员和本人可以删除
        if(!post.getUserId().equals(loginUser.getId()) && !userService.isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = postService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     *
     *
     * @description: 帖子更新
     * @param postUpdateRequest
     * @param request
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/17 20:14
     */

    @PostMapping("/update")
    public BaseResponse<Boolean> updatePost(@RequestBody PostUpdateRequest postUpdateRequest,HttpServletRequest request){
        if(postUpdateRequest==null || postUpdateRequest.getId()<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post=new Post();
        BeanUtils.copyProperties(postUpdateRequest,post);
        //参数校验
        postService.validPost(post,false);
        User loginUser = userService.getLoginUser(request);
        Long id = postUpdateRequest.getId();
        //判断是否存在
        Post oldPost = postService.getById(id);
        if(oldPost==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //仅本人和管理员可以修改
        if(!oldPost.getUserId().equals(loginUser.getId()) && !userService.isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = postService.updateById(post);
        return ResultUtils.success(b);
    }

    /**
     *
     *
     * @description: 根据id获取帖子信息
     * @param id
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/17 20:18
     */

    @GetMapping("/get")
    public BaseResponse<Post> getPostById(Long id){
        if(id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = postService.getById(id);
        if(post.getIsDelete()==1){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"帖子已删除");
        }
        return ResultUtils.success(post);
    }

    /**
     *
     *
     * @description: 获取帖子列表，仅管理员可以使用
     * @param postQueryRequest
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/17 20:21
     */

    @GetMapping("/list")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<List<Post>> listPost(PostQueryRequest postQueryRequest){
        Post postQuery=new Post();
        if(postQueryRequest!=null){
            BeanUtils.copyProperties(postQueryRequest,postQuery);
        }
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<>(postQuery);
        List<Post> postList = postService.list(postQueryWrapper);
        return ResultUtils.success(postList);
    }

    /**
     *
     *
     * @description: 分页获取帖子列表
     * @param postQueryRequest
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/17 20:33
     */

    @GetMapping("/list/page")
    public BaseResponse<Page<Post>> listPostByPage(PostQueryRequest postQueryRequest){
        if(postQueryRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = new Post();
        BeanUtils.copyProperties(postQueryRequest,post);
        long current = postQueryRequest.getCurrent();
        long pageSize = postQueryRequest.getPageSize();
        String sortField = postQueryRequest.getSortField();
        String sortOrder = postQueryRequest.getSortOrder();
        String content = post.getContent();
        //content需要支持模糊搜索
        post.setContent(null);
        //限制爬虫
        if(pageSize>50){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<>(post);
        postQueryWrapper.like(StringUtils.isNotBlank(content),"content",content);
        postQueryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),sortField);
        Page<Post> page = postService.page(new Page<>(current, pageSize), postQueryWrapper);
        return ResultUtils.success(page);
    }
}
